package com.daocao.jy.view.uploadImage;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.View;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.daocao.jy.R;
import com.daocao.jy.util.ImageUtil;
import com.daocao.jy.util.ToastUtil;

//import com.mob.tools.utils.BitmapHelper;


/**
 * 上传头像功能封装
 * 必须在使用此adapter页面监听欧尼ActivityResult方法，执行adapter.onActivityResult(requestCode, resultCode, data)
 * Created by maodq on 16/4/29.
 */
public class UploadImgAdapter {
    // 可自定义文件目录名
    private static final String ROOT_NAME = "UPLOAD_CACHE";
    private final String TAG = "UploadImgAdapter";

    private Activity mActivity;
    private File mTempCameraFile;
    private File mTempCropFile;
    public static final int MODE_HEAD = 0;
    public static final int MODE_IMG = 1;


    private static final int ALBUM_REQUEST_CODE = 1;
    private static final int CAMERA_REQUEST_CODE = 2;
    private static final int CROP_REQUEST_CODE = 4;
    Action2 mOnImageUpdateListener;
    private ProgressDialog mProgressDialog;
    private int mMode = -1;
    private QuickOptionDialog mDialog;

    public UploadImgAdapter(Activity activity, Action2 l) {
        mActivity = activity;
        mOnImageUpdateListener = l;
        mDialog = new QuickOptionDialog(mActivity);
        mDialog.setCancelable(true);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setOnQuickOptionformClickListener(new QuickOptionDialog.OnQuickOptionFormClick() {
            @Override
            public void onQuickOptionClick(View v) {
                clickQuickOption(v);
            }
        });
    }

    public UploadImgAdapter showDialog() {
        if (mMode == -1)
            throw new IllegalStateException("请通过withMode(mode)方法设置执行图片模式");
        mDialog.show();
        return this;
    }

    public UploadImgAdapter withMode(int mode) {
        mMode = mode;
        return this;
    }

    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};


    // 头像dialog点击监听器
    private void clickQuickOption(View v) {
        switch (v.getId()) {
            case R.id.tv_photograph:
//                if (Build.VERSION.SDK_INT >= 23) {
//                    int storagePermission = ActivityCompat.checkSelfPermission(mActivity,
//                            Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                    int cameraPermission = ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA);
//                    if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
//                        ActivityCompat.requestPermissions(mActivity, PERMISSIONS_CAMERA_AND_STORAGE,
//                                100);
//                        return;
//                    } else {
//                        Intent cameraIntent;
//                        if (Build.VERSION.SDK_INT < 24) {
//                            cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                            mActivity.startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
//                        } else {
////                            判断7.0的文件系统
//
//
//                            cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//                            mActivity.startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
//                        }
//                    }
//                } else {
//                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    mActivity.startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
//                }
                if (Build.VERSION.SDK_INT >= 23) {
                    Intent cameraIntent;
                    if (Build.VERSION.SDK_INT < 24) {
                        cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempCameraFile()));
                        mActivity.startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                    } else {
                        cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        Uri apkUri = FileProvider.getUriForFile(mActivity, "com.daocao.jy.fileprovider", getTempCameraFile());
                        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, apkUri);
                        mActivity.startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                    }
                } else {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempCameraFile()));
                    mActivity.startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
                }


                break;
            case R.id.tv_select:


                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                mActivity.startActivityForResult(intent, ALBUM_REQUEST_CODE);
                break;
            case R.id.tv_cancel:
                // 默认不做处理也会自动关闭dialog
            default:
                break;
        }
    }


    private static Uri getUriForFile(Activity context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.daocao.jy.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }


    //    使用activity的onActivityResult，调用此方法
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE:       // 照相机返回结果
                    if (mMode == MODE_IMG) {
//                        Bundle extras = data.getExtras();
//                        Bitmap mImageBitmap = (Bitmap) extras.get("data");

                        if (!mTempCameraFile.exists()) {
                            ToastUtil.makeText(mActivity, "找不到此图片").show();
                            return;
                        }
                        // 可以在这里统一进行联网上传操作，把上传结果传回，也可以直接传file交给原页面处理
                        mOnImageUpdateListener.call(ImageUtil.getimage(mTempCameraFile.getAbsolutePath(), 800, 800, 70), mMode);
                    } else if (mMode == MODE_HEAD) {
                        // 头像宽高为65dp,对应xxxhdpi为260px
                        startCrop(Uri.fromFile(mTempCameraFile), 400, 400);
                    }
                    break;
                case ALBUM_REQUEST_CODE:        // 相册返回结果
                    Uri uri = data.getData();
                    if (mMode == MODE_IMG) {
//                        File file = BitmapHelper.decodeUriAsFile(mActivity, uri);
//                        file = composBitmap(file);
                        sendImage(uri);
                    } else if (mMode == MODE_HEAD) {
                        startCrop(uri, 400, 400);
                    }
                    break;
                case CROP_REQUEST_CODE:         // 裁剪返回结果
                    sendImage(data.getData());
                    break;
            }
        }
    }

    /**
     * 开始裁剪
     * 附加选项	   数据类型	    描述
     * crop	        String	    发送裁剪信号
     * aspectX	    int	        X方向上的比例
     * aspectY	    int	        Y方向上的比例
     * outputX	    int	        裁剪区的宽
     * outputY	    int	        裁剪区的高
     * scale	    boolean	    是否保留比例
     * return-data	boolean	    是否将数据保留在Bitmap中返回
     * data	        Parcelable	相应的Bitmap数据
     * circleCrop	String	    圆形裁剪区域？
     * MediaStore.EXTRA_OUTPUT ("output")	URI	将URI指向相应的file:///...
     *
     * @param uri uri
     */
    private void startCrop(Uri uri, int outputX, int outputY) {
//        Bitmap bitmap = null;
//        String str = "";
//
//        try {
////            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//            bitmap = getThumbnail(uri, 500);
//            str = MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        if (bitmap == null || TextUtils.isEmpty(str)) {
//            Toast.makeText(mActivity, "找不到此图片", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        uri = Uri.parse(str);

        Intent intent = new Intent("com.android.camera.action.CROP"); //调用Android系统自带的一个图片剪裁页面
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//进行修剪
        // aspectX aspectY 是宽高的比例
        if (outputX == outputY) {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        } else {
            intent.putExtra("scale", true);
        }
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempCropFile()));
        mActivity.startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    private ContentResolver getContentResolver() {
        return mActivity.getContentResolver();
    }

    private File getTempCropFile() {
        if (mTempCropFile == null) {
            mTempCropFile = getTempMediaFile();
        }
        return mTempCropFile;
    }

    private File getTempCameraFile() {
        if (mTempCameraFile == null)
            mTempCameraFile = getTempMediaFile();
        return mTempCameraFile;
    }

//    private File composBitmap(File file) {
//        Bitmap bitmap = BitmapHelper.revisionImageSize(file);
//        return BitmapHelper.saveBitmap2file(mActivity, bitmap);
//    }

    private void sendImage(Uri file) {
        if (file == null) {
            ToastUtil.makeText(mActivity, "找不到此图片");
            return;
        }


        // 可以在这里统一进行联网上传操作，把上传结果传回，也可以直接传file交给原页面处理
        try {
            mOnImageUpdateListener.call(getBitmapFormUri(mActivity, file), mMode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 原项目用的RxJava的Action2
     */
    public interface Action2 {
        void call(Bitmap file, int mode);
    }

    public static Bitmap getBitmapFormUri(Activity ac, Uri uri) throws FileNotFoundException, IOException {
        InputStream input = ac.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        int originalWidth = onlyBoundsOptions.outWidth;
        int originalHeight = onlyBoundsOptions.outHeight;
        if ((originalWidth == -1) || (originalHeight == -1))
            return null;
        //图片分辨率以480x800为标准
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (originalWidth > originalHeight && originalWidth > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (originalWidth / ww);
        } else if (originalWidth < originalHeight && originalHeight > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (originalHeight / hh);
        }
        if (be <= 0)
            be = 1;
        //比例压缩
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = be;//设置缩放比例
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = ac.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();

        return compressImage(bitmap);//再进行质量压缩
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            //第一个参数 ：图片格式 ，第二个参数： 图片质量，100为最高，0为最差  ，第三个参数：保存压缩后的数据的流
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = //把ByteArrayInputStream数据生成图片
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    /**
     * 获取相机的file
     */
    public File getTempMediaFile() {
        File file = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            String fileName = getTempMediaFileName();
            file = new File(fileName);
        }
        return file;
    }

    public String getTempMediaFileName() {
        return getParentPath() + "image" + System.currentTimeMillis() + ".jpg";
    }

    private String getParentPath() {
        String parent = Environment.getExternalStorageDirectory()
                + File.separator + ROOT_NAME + File.separator;
        mkdirs(parent);
        return parent;
    }

    public boolean mkdirs(String path) {
        File file = new File(path);
        return !file.exists() && file.mkdirs();
    }
}
